<?php

/*
    Order controller provides functionality related to ordering tickets.
    All users can order tickets.
 */

class Controller_Order extends Controller_Template {
    private $user_data;
    private $user_id;
    private $language;
    
    public function before() {
        $this->language = Cookie::get((Auth::check() ? 'user' : 'guest') . '_language', 'lv');
        Config::set("language", $this->language);
        Lang::load('main', null, $this->language, true);
        
        parent::before();
        $this->user_data = Auth::instance();
        $this->user_id = $this->user_data->get_user_id();
        
        $this->template->language = $this->language;
        $this->template->genres = Model_Orm_Genre::find('all');
        $this->template->cinema_info = Model_Orm_Cinema::find('first');
    }
    
    public function action_new($show = null) {
/*      if(Session::get('order_success')) {
            $order_info = explode('|', Session::get('order_success'));
            
            $mail_text =    "Biļešu informācija: http://test.cinema.is/order/printview/". $order_info[1] .
                            " Apmaksas info: xxxxxxx" . 
                            " Kino IS";
            
            $this->send_email($order_info[0], $mail_text);
        }
*/
        is_null($show) and Response::redirect('/');
        
        $show_info = Model_Orm_Show::find($show);
        
        //If show is not found, redirect to main page.
        is_null($show_info) and Response::redirect('/');
        
        $movie_info = $show_info->get('movie');
        $auditorium_info = $show_info->get('auditorium');
        $orders_info = $show_info->get('orders');
        
        $reserved_seats = array();
        
        //Collecting info about reserved seats.
        foreach($orders_info as $order) {
            $reservation_info = $order->get('reservations');
            
            foreach($reservation_info as $reservation) {
                array_push($reserved_seats, array('row' => $reservation['row'], 'seat' => $reservation['seat']));
            }
        }
        
        if(Input::method() == "POST") {

            //Retrieving info about reserved seats.
            $seat_info = json_decode(Input::post('Chosen_Seats'), true);     
            
            if(empty($seat_info))
            {
                Session::set_flash('error', 'Lūdzu, izvēlieties vismaz vietu sēdvietu !');
                Response::redirect('order/new/'.$show);
            }
            
            $unavailable_seats = array();
            
            //Checking if user has selected unavailable (already reserved) seats
            foreach($seat_info as $chosen_seat) {
                foreach($reserved_seats as $reserved_seat) {
                    if($reserved_seat['row'] == $chosen_seat['row'] && $reserved_seat['seat'] == $chosen_seat['seat']) {
                        array_push($unavailable_seats, array('row' => $chosen_seat['row'], 'seat' => $chosen_seat['seat']));
                    }
                }
            }
            
            if(count($unavailable_seats) === 0) {
                $validation = Model_Orm_Order::validate('add');
                if($validation->run()) {
                    $new_order = new Model_Orm_Order();
                    $new_order->first_name = $validation->validated("First_name");
                    $new_order->last_name = $validation->validated("Last_name");
                    $new_order->email = $validation->validated("Email");
                    $new_order->phone_nr = $validation->validated("Phone");
                    $new_order->user_id = $this->user_id[1];
                    $new_order->show_id = Input::post('Show_ID');
                    $new_order->purchase_time = time();
                    $new_order->is_paid = 0;
                    $new_order->save();
                    
                    $newest_order_id = Model_Orm_Order::query()->max('id');
                    
                    //After order has been saved, save the reserved seats.
                    foreach($seat_info as $seat) {
                        $new_reservation = new Model_Orm_Reservation();
                        $new_reservation->order_id = $newest_order_id;
                        $new_reservation->row = $seat['row'];
                        $new_reservation->seat = $seat['seat'];
                        
                        $new_reservation->save();
                    }
                    
//                  Session::set('order_success', $validation->validated("Email") .'|' . $newest_order_id);
                    $mail_text =    "Biļešu informācija: http://test.cinema.is/order/printview/". $newest_order_id .
                                    " Apmaksas info: xxxxxxx" . 
                                    " Kino IS";
                    
                    $this->send_email($validation->validated("Email"), $mail_text);
                    
                    Session::set_flash('success', 'Biļetes veiksmīgi iegādātas ! Sīkāka informācija nosūtīta uz Jūsu e-pastu.');
                    Response::redirect('order/new/'.$show);
                } else {
                    Session::set_flash('error', $validation->error_message());
                    Response::redirect('order/new/'.$show);
                }
            } else {
                Session::set_flash('error', 'Izvēlētā(-s) sēdvieta(-s) ir aizņemtas !');
                Response::redirect('order/new/'.$show);
            } 
        }
        
        $view_ticket_purchase = View::forge('order/new');
        $this->template->page_custom_scripts = array('ticket_reservation.js');
        $view_ticket_purchase->set("show_info", $show_info);
        $view_ticket_purchase->set("movie_info", $movie_info);
        $view_ticket_purchase->set("auditorium_info", $auditorium_info);
        $view_ticket_purchase->set("language", $this->language);
        $view_ticket_purchase->set("reserved_seats", $reserved_seats);
        $this->template->page_content = $view_ticket_purchase;
    }
    
    public function send_email($send_to, $mail_text = '') {
        $email = Email::forge();
        $email->from('janis.zusans@gmail.com', 'Cinema IS');

        $email->to($send_to, 'Cinema IS');
        $email->subject('Biļešu iegāde');
        
        $email->body($mail_text);
        $email->send();
    }
    
    public function action_printview($order_id = null) {
        is_null($order_id) and Response::redirect('/');
        
        $order_data = Model_Orm_Order::find($order_id);
        
        is_null($order_data) and Response::redirect('/');
        
        if($order_data->user_id == 0) {
            $view_ticket_view = View::forge('order/guest_view');
            $view_ticket_view->set('order_data', $order_data);
            $this->template->page_content = $view_ticket_view;
        } else {
            if($this->user_id[1] != $order_data->user_id) {
                Response::redirect('/');
            }

            $reservation_data = $order_data->get('reservations');
            $show_data = $order_data->get('show');
            $auditorium_data = $show_data->get('auditorium');
            $movie_data = $show_data->get('movie');
            $cinema_data = Model_Orm_Cinema::find('first');



            $view = View::forge('order/print_view');
            $view->set('reservation_data', $reservation_data);
            $view->set('order_data', $order_data);
            $view->set('show_data', $show_data);
            $view->set('movie_data', $movie_data);
            $view->set('cinema_data', $cinema_data);
            $view->set('auditorium_data', $auditorium_data);

            //Returning only view, w/o template.
            return $view;   
        }
    }
    
    //Guests have to confirm their email before being able to view ordered tickets.
    public function action_verifyEmail() {
        if(Input::method() !== "POST") {
            Response::redirect('/');
        }
        
        $order_data = Model_Orm_Order::find(Input::post('Order_ID'));
        
        is_null($order_data) and Response::redirect('/');
        
        if($order_data->email == Input::post('Email')) {
            
            //Collecting all the info necessary for tickets
            $reservation_data = $order_data->get('reservations');
            $show_data = $order_data->get('show');
            $auditorium_data = $show_data->get('auditorium');
            $movie_data = $show_data->get('movie');
            $cinema_data = Model_Orm_Cinema::find('first');

            $view = View::forge('order/print_view');
            $view->set('reservation_data', $reservation_data);
            $view->set('order_data', $order_data);
            $view->set('show_data', $show_data);
            $view->set('movie_data', $movie_data);
            $view->set('cinema_data', $cinema_data);
            $view->set('auditorium_data', $auditorium_data);

            return $view;
        } else {
            Session::set_flash('error', 'Ievadīta nepareiza e-pasta adrese !');
            Response::redirect('/');
        }
    }
}
